package com.education.ai.interceptor;

import com.education.ai.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    
    @Autowired
    private AuthService authService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        logger.debug("拦截请求: {}, 方法: {}", requestURI, request.getMethod());
        
        // 放行OPTIONS请求
        if ("OPTIONS".equals(request.getMethod())) {
            logger.debug("放行OPTIONS请求");
            return true;
        }
        
        // 获取请求头中的token
        String authorization = request.getHeader("Authorization");
        logger.debug("Authorization头: {}", authorization);
        
        // 验证token
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String userId = authService.getUserIdFromToken(authorization);
            Integer userRole = authService.getUserRoleFromToken(authorization);
            
            if (userId != null) {
                // 将用户ID放入请求属性
                request.setAttribute("userId", userId);
                
                // 根据角色类型设置特定属性
                if (userRole != null) {
                    if (userRole == 1) {
                        // 教师
                        request.setAttribute("teacherId", userId);
                        logger.debug("认证成功，教师ID: {}", userId);
                    } else if (userRole == 2) {
                        // 学生
                        request.setAttribute("studentId", userId);
                        logger.debug("认证成功，学生ID: {}", userId);
                    } else if (userRole == 3) {
                        // 管理员
                        request.setAttribute("adminId", userId);
                        logger.debug("认证成功，管理员ID: {}", userId);
                    }
                }
                
                return true;
            } else {
                logger.warn("Token无效或已过期: {}", authorization);
            }
        } else {
            logger.warn("缺少Authorization头或格式不正确: {}", authorization);
        }
        
        // 认证失败
        logger.warn("认证失败，拦截请求: {}", requestURI);
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        try (PrintWriter writer = response.getWriter()) {
            writer.write("{\"success\":false,\"message\":\"认证失败，请重新登录\",\"code\":401}");
            writer.flush();
        }
        
        return false;
    }
} 